const path = require('path')
const CompressionPlugin = require('compression-webpack-plugin')

// 判断是否为生产环境
const isProduction = process.env.NODE_ENV === 'production'

module.exports = {

  // 部署应用包时的基本URL
  // publicPath: process.env.VUE_APP_PUBLIC_PATH || '/',
  publicPath: process.env.NODE_ENV === 'production' ? '/vue-app' : '/',
  // 输出文件目录
  outputDir: 'dist',

  // 静态资源目录
  assetsDir: 'static',

  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,

  // 开发服务器配置
  devServer: {
    port: 8080,
    open: true,
    // 配置代理        
    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: process.env.VUE_APP_SERVICE_URL,
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: '/api'
        }
      }
    },
    // 配置history模式下的刷新处理
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join('/', 'index.html') }
      ]
    },
  },

  // webpack配置
  configureWebpack: config => {
    // 配置路径别名
    config.resolve.alias = {
      ...config.resolve.alias,
      '@': path.resolve(__dirname, 'src')
    }


    // 生产环境配置
    if (isProduction) {
      // 开启gzip压缩
      config.plugins.push(
        new CompressionPlugin({
          algorithm: 'gzip',
          test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
          threshold: 10240,
          minRatio: 0.8,
          deleteOriginalAssets: false
        })
      )

      // 优化分包
      config.optimization = {
        ...config.optimization,
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial'
            },
            elementUI: {
              name: 'chunk-elementUI',
              priority: 20,
              test: /[\\/]node_modules[\\/]element-ui[\\/]/
            },
            commons: {
              name: 'chunk-commons',
              test: path.resolve(__dirname, 'src/components'),
              minChunks: 2,
              priority: 5,
              reuseExistingChunk: true
            }
          }
        }
      }
    }
  },



  // CSS相关配置
  css: {
    // 是否使用css分离插件
    extract: isProduction,
    // 开启 CSS source maps
    sourceMap: false,
    // css预设器配置项
    loaderOptions: {
      // 更新为sass选项，适配dart-sass
      sass: {
        // 注意：在sass-loader v8中，这个选项名是"prependData"
        // 在sass-loader v10中，这个选项名是"additionalData"
        additionalData: `
          @import "~@/styles/variables.scss";
        `
      }
    }
  }
}
